<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\model\Advice;
use app\common\model\Area;
use app\common\model\Comment;
use app\common\model\Deposit;
use app\common\model\WorkerInfo;
use app\common\model\WorkerSelection;
use app\common\model\User;
use app\common\model\Order;
use app\common\model\WorkLog;
use app\common\service\Pay;
use think\Exception;
use think\facade\Db;

class Worker extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 陪诊员信息选项
     */
    public function selection(){
        $list=[
            'gender'=>[],
            'marriage'=>[],
            'education'=>[],
            'experience'=>[],
            'ethnic'=>[],
            'born'=>[]
        ];

        $selection=WorkerSelection::order('weigh asc')->select()?:[];
        foreach ($selection as $s){
            if(!in_array($s['code'],['gender','marriage','education','experience','ethnic','born'])){
                continue;
            }
            $list[$s['code']][]=$s['name'];
        }

        $this->success('成功',$list);
    }

    /**
     * 申请陪诊员
     */
    public function apply(){
        $user=$this->auth->getUser();

        $type       =request()->param('type')?:0;
        $name       =request()->param('name');
        $age        =request()->param('age');
        $mobile     =request()->param('mobile');
        $province   =request()->param('province');
        $city       =request()->param('city');
        $county     =request()->param('county');
        $intro      =request()->param('intro','');

        $gender     =request()->param('gender');
        $marriage   =request()->param('marriage','');
        $education  =request()->param('education','');
        $experience =request()->param('experience','');
        $ethnic     =request()->param('ethnic','');
        $born       =request()->param('born','');

        $id_no=request()->param('id_no')?:'';

        $worker=WorkerInfo::where(['user_id'=>$user['id']])->find()?:[];
        if($worker){
            if($type==0&&$worker['pzy_status']!='none')
                $this->error('已提交过陪诊员申请，请勿重复提交');
            if($type==1&&$worker['phy_status']!='none')
                $this->error('已提交过陪护员申请，请勿重复提交');
        }

        if(!$name){
            $this->error('请填写姓名');
        }
        if(!$gender){
            $this->error('请选择性别');
        }
        if(!$age){
            $this->error('请填写年龄');
        }
        if(!$mobile){
            $this->error('请填写联系电话');
        }

        if(!$province||!$city||!$county)
            $this->error('请完善地址信息');

        if(!$marriage){
            $this->error('请选择婚姻状况');
        }
        if(!$education){
            $this->error('请选择学历');
        }
        if(!$experience){
            $this->error('请选择工作经验');
        }
        /*if(!$ethnic){
            $this->error('请选择民族');
        }
        if(!$born){
            $this->error('请选择属相');
        }*/


        if(!$id_no)
            $this->error('请填写身份证号');

        $province=Area::where(['name'=>$province])->find()?:[];
        if(!$province)
            $this->error('未找到此省份信息');

        $city=Area::where(['name'=>$city])->find()?:[];
        if(!$city)
            $this->error('未找到此城市信息');

        $county=Area::where(['name'=>$county])->find()?:[];
        if(!$county)
            $this->error('未找到此区县信息');


        Db::startTrans();
        try {
            $worker['user_id']      =$user['id'];
            $worker['name']         =$name;
            $worker['age']          =$age;
            $worker['mobile']       =$mobile;
            $worker['address']      =$province['name'].'/'.$city['name'].'/'.$county['name'];
            $worker['province']     =$province['id'];
            $worker['city']         =$city['id'];
            $worker['county']       =$county['id'];
            $worker['intro']        =$intro;
            $worker['gender']       =$gender;
            $worker['marriage']     =$marriage;
            $worker['education']    =$education;
            $worker['experience']   =$experience;
            $worker['ethnic']       =$ethnic;
            $worker['born']         =$born;
            $worker['id_no']        =$id_no;

            if(!isset($worker)){
                $worker['create_time']=time();
            }
            if($type==0){
                $worker['pzy_status']='reviewing';
                $user['pzy_status']='reviewing';
            }
            if($type==1){
                $worker['phy_status']='reviewing';
                $user['phy_status']='reviewing';
            }
            $user->save();

            if(isset($worker['id'])){
                $worker->save();
            }
            else{
                WorkerInfo::insert($worker);
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('申请已提交');
    }

    public function info(){
        $id=request()->param('id');

        $worker= WorkerInfo::alias('WF')
            ->leftJoin('user U','WF.user_id=U.id')
            ->where(['WF.user_id'=>$id])
            ->field('WF.*,U.working_status,U.is_spare,U.worker_score,U.avatar')
            ->find()?:[];

        if(!$worker){
            $this->error('未找到此陪诊员信息');
        }

        $worker['spare_status']= (new User)->fetchSpareStatus($worker);

        $img=[];

        if($worker['pzy_status']=='normal'){
            $pzy_img=config('site.pzy_img')?cdnurl(config('site.pzy_img'),true):'';
            if($pzy_img){
                $img[]=$pzy_img;
            }
        }
        if($worker['phy_status']=='normal'){
            $phy_img=config('site.phy_img')?cdnurl(config('site.phy_img'),true):'';
            if($phy_img){
                $img[]=$phy_img;
            }
        }
        $worker['img']=$img;

        $this->success('成功',$worker);
    }

    /**
     * 上/下班
     */
    public function online(){
        $user=$this->auth->getUser();

        $spare_status=request()->param('spare_status');

        if(!in_array($spare_status,[0,1,2]))
            $this->error('参数错误');

        switch ($spare_status){
            case 0:
                $user['is_spare']=1;
                $user['working_status']=0;
                break;
            case 1:
                $user['working_status']=1;
                $user['is_spare']=1;
                break;
            case 2:
                $user['working_status']=1;
                $user['is_spare']=0;
        }
        $user->save();
        //(new User)->spare($user['id']);
        $this->success('成功');
    }

    /**
     * 评价列表
     */
    public function comment(){
        $user=$this->auth->getUser();
        $page=request()->param('page',1);

        $list=Comment::with([
                'user',
                'order1'=>function($query){
                    $query->with(['hospital','patient','servicebasic']);
                }
            ])
            ->where([
                'target_id'=>$user['id'],
                'type'=>0
            ])
            ->page($page,10)
            ->order('create_time desc')
            ->select()?:[];

        foreach ($list as $l){
            $l->visible([
                'content','create_time','score','user_id',
                'user'=>['avatar','username'],
                'order1'=>[
                    'patient'=>['name'],
                    'servicebasic'=>['code','name'],
                    'hospital'=>['name'],
                ],
            ]);
        }

        $this->success('成功',$list);
    }

    /**
     * 意见反馈
     */
    public function advice(){
        $user=$this->auth->getUser();

        $content=request()->param('content');

        if(!$content)
            $this->error('请填写内容');

        $check_exist=Advice::where([
            ['user_id','=',$user['id']],
            ['create_time','>',time()-43200]
        ])
        ->find()?:[];
        if($check_exist)
            $this->error('12内提交过意见反馈，请过段时间再提交新的反馈');

        $result=Advice::insert([
            'user_id'=>$user['id'],
            'content'=>$content,
            'create_time'=>time()
        ]);

        if($result)
            $this->success('成功');
        else
            $this->error('添加意见反馈出错');
    }


    public function deposit(){
        $user=$this->auth->getUser();
        $worker=WorkerInfo::where([['user_id','=',$user['id']]])->find()?:[];
        if(!$worker){
            $this->error('未找到陪诊员信息');
        }

        $money=config('site.deposit')?:0;
        if(!$money){
            $this->error('获取押金金额出错');
        }

        if($worker['pzy_status']=='normal'||$worker['phy_status']=='normal'){
            $deposit=Deposit::where(['user_id'=>$user['id'],'status'=>1])->find()?:[];
            if(!$deposit){
                $money=$worker['deposit'];
            }
            else{
                $money=$deposit['money'];
            }
            $str='无需支付保证金';
            $status='normal';
        }
        elseif($worker['pzy_status']=='unpaid'||$worker['phy_status']=='unpaid'){
            $str='请支付保证金';
            $status='unpaid';
        }
        else{
            $str='陪诊员状态不可支付保证金';
            $status='trash';
        }


        $this->success($str,['status'=>$status,'money'=>$money]);
    }

    public function depositPay(){
        $user=$this->auth->getUser();
        $worker=WorkerInfo::where([['user_id','=',$user['id']]])->find()?:[];

        $check_deposit=Deposit::where(['user_id'=>$user['id'],'status'=>1])->find()?:[];
        if($check_deposit){
            if($worker['pzy_status']=='unpaid'){
                $worker['pzy_status']=='normal';
                $worker->save();
            }
            if($worker['phy_status']=='unpaid'){
                $worker['pzy_status']=='normal';
                $worker->save();
            }
            $this->error('此账号已支付过保证金。');
        }
        if($worker['pzy_status']=='normal'||$worker['phy_status']=='normal'){
            if($worker['pzy_status']=='unpaid'){
                $worker['pzy_status']=='normal';
                $worker->save();
            }
            if($worker['phy_status']=='unpaid'){
                $worker['pzy_status']=='normal';
                $worker->save();
            }
            $this->error('此陪诊员为正常状态，无需再支付保证金');
        }

        if($worker['pzy_status']!='unpaid'&&$worker['phy_status']!='unpaid'){
            if($worker['pzy_status']=='refused'||$worker['phy_status']=='refused'){
                $this->error('此陪诊员审核不通过，请联系客服。');
            }
            if($worker['pzy_status']=='reviewing'||$worker['phy_status']=='reviewing'){
                $this->error('此陪诊员正在审核中，请耐心等待。');
            }
            if($worker['pzy_status']=='trash'||$worker['phy_status']=='trash'){
                $this->error('此陪诊员已停用，请联系客服。');
            }
            if($worker['pzy_status']=='deleted'||$worker['phy_status']=='deleted'){
                $this->error('此陪诊员已停用，请联系客服。');
            }
        }

        $money=config('site.deposit')?:0;
        if(!$money){
            $this->error('获取押金金额出错');
        }

        $order=[
            'user_id'=>$user['id'],
            'money'=>$money,
            'status'=>0,
            'order_sn'=>'D'.makePaySn($user['id']),
            'create_time'=>time()
        ];


        $exist=Deposit::where(['user_id'=>$user['id'],'status'=>0])->find()?:[];
        if($exist){
            if($exist['money']!=$money){
                $exist['status']=10;
                $exist->save();
                Deposit::insert($order);
            }
            else{
                $order=$exist;
            }
        }
        else{
            Deposit::insert($order);
        }

        $appid=config('site.worker_miniapp_appid');
        if(!$appid){
            $this->error('缺少appid，请联系客服解决');
        }
        if(!$user['worker_wx_miniapp_openid']){
            $this->error('缺少openid');
        }


        //回调链接
        $notifyurl = $this->request->root(true) . '/worker/notify/order_sn/' . $order['order_sn'];
        $returnurl = $this->request->root(true) . '/worker/notify/order_sn/' . $order['order_sn'];
        $response  = Service::submitOrder(
            $order['money'],
            $order['order_sn'],
            'wechat',
            '陪诊员保证金支付',
            $notifyurl,
            $returnurl,
            'miniapp',
            $user['worker_wx_miniapp_openid'],
            $appid
        );
        adlog('陪诊员保证金-支付参数',$response);

        $this->success('获取支付参数成功',['response' => json_decode($response)]);
    }


    public function notify(){
        adlog('陪诊员保证金-支付回调原本',file_get_contents("php://input"));
        $pay     = Service::checkNotify('wechat');
        if (!$pay) {
            echo '验签失败';
            return 'failed';
        }
        $data = $pay->verify();
        adlog('陪诊员保证金-支付回调',$data);
        Db::startTrans();
        try {
            $order_sn   = request()->param('order_sn')?:'';
            $order = Deposit::get(['order_sn' => $order_sn,'status' => [0,10]]);
            if(!$order){
                throw new Exception('未找到对应订单');
            }
            if ($order) {
                $order['pay_time']=time();
                $order['status']=1;

                $user=User::get($order['user_id']);
                if(!$user){
                    throw new Exception("未找到用户信息。user_id:{$order['user_id']}");
                }

                $worker=WorkerInfo::where(['user_id'=>$order['user_id']])->find();
                if(!$worker){
                    throw new Exception("未找到陪诊员信息。user_id:{$order['user_id']}");
                }


                if($worker['pzy_status']=='unpaid'){
                    $worker['pzy_status']=='normal';
                }
                if($worker['phy_status']=='unpaid'){
                    $worker['pzy_status']=='normal';
                }
                $worker['deposit']=$order['money'];
                $worker->save();
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            //$this->error($e->getMessage());
            adlog('陪诊员保证金-支付错误信息',$e->getMessage());
            exit;
        }
        return 'success';
    }

    /**
     * 保证金退款
     */
    public function depositRefund(){
        $user=$this->auth->getUser();
        $worker=WorkerInfo::where([['user_id','=',$user['id']]])->find()?:[];
        if(!$worker){
            $this->error('非陪诊员，不可使用此功能');
        }

        $deposit=Deposit::where(['user_id'=>$user['id'],'status'=>1])->find()?:[];
        if(!$deposit){
            $this->error('未找到保证金付款记录');
        }

        if(time()>=$deposit['pay_time']+365*86400){
            $this->error('保证金支付已超过一年，请联系客服退款。');
        }


        $result=Pay::refund([
            'order_sn'=>$deposit['order_sn'],
            'pay_price'=>$deposit['money']
        ],'陪诊员保证金退款');

        if(!$result){
            $this->error('退款失败');
        }

        $deposit['status']=2;
        $deposit['refund_time']=time();
        $deposit->save();

        if($worker['pzy_status']=='normal'){
            $worker['pzy_status']=='unpaid';
        }
        if($worker['phy_status']=='normal'){
            $worker['phy_status']=='unpaid';
        }
        $worker['deposit']=0;
        $worker->save();

        $this->success('成功');
    }



    public function workLog(){
        $user=$this->auth->getUser();
        $order_id=request()->param('order_id')?:0;


        $order=Order::with([
                'user',
                'patient',
                'worker'=>function($query){
                    $query->with(['workerInfo']);
                },
                'servicebasic',
                'hospital',
                'department',
                'address'
            ])
            ->where([
                'id'=>$order_id,
            ])->find()?:[];
        if(!$order){$this->error('未找到对应订单信息');}

        if($order['status']!=6){$this->error("订单状态不为'已经结束',不可提交工作日志");}
        if($user['id']!=$order['worker_id']){$this->error('您非本订单陪诊员，不可提交工作日志');}


        $data=[
            'worker_id'             =>$user['id'],
            'order_id'              =>$order_id,
            'area'                  =>$order['hospital']?$order['hospital']['area']:'',
            'code'                  =>$order['code'],
            'log_note'              =>request()->param('log_note')?:'',
            'log_attachment'        =>request()->param('log_attachment')?:'',
            'document_type'         =>'居民二代身份证',
            'document_no'           =>$order['patient']?$order['patient']['id_no']:'',
            'phone'                 =>in_array($order['code'],['severe_illness','oversea','private_doctor','famous_doctor'])?$order['phone']:$order['patient']['mobile'],
            'feedback'              =>request()->param('feedback')?:'',
            'hospital'              =>$order['hospital']?$order['hospital']['name']:'',
            'department'            =>$order['department']?$order['department']['name']:'',
            'doctor'                =>request()->param('doctor')?:'',
            'service_date'          =>$order['begin_time'],
            'patient_name'          =>$order['patient']?$order['patient']['name']:'',
            'worker_name'           =>$order['worker']?($order['worker']['workerInfo']?$order['worker']['workerInfo']['name']:''):'',
            'worker_arrive_time'    =>request()->param('worker_arrive_time'),
            'patient_arrive_time'   =>request()->param('patient_arrive_time'),
            'diagnose_begin_time'   =>request()->param('diagnose_begin_time'),
            'diagnose_end_time'     =>request()->param('diagnose_end_time'),
            'examine'               =>request()->param('examine'),
            'examine_time'          =>request()->param('examine_time'),
            'examine_name'          =>request()->param('examine_name'),
            'medicine'              =>request()->param('medicine'),
            'medicine_time'         =>request()->param('medicine_time'),
            'reexamine'             =>request()->param('reexamine'),
            'result'                =>request()->param('result'),
            'patient_leave_time'    =>request()->param('patient_leave_time'),
            'patient_unhappy'       =>request()->param('patient_unhappy'),
            'create_time'           =>time()
        ];

        if(!$data['worker_arrive_time']){$this->error('请选择陪诊员到医院时间');}

        if($data['examine']){
            if(!$data['examine_time']){$this->error('请选择检查时间');}
            if(!$data['examine_name']){$this->error('请填写检查项目');}
        }

        if($data['medicine']){
            if(!$data['medicine_time']){$this->error('请选择取药时间');}
        }

        Db::startTrans();
        try {

            WorkLog::insert($data);


            if(!$order['complete_time']){

                if($order['inviter_money']>0){
                    User::money($order['inviter_money'],$order['inviter_id'],'订单完成，推荐人分成',$order['user_id']);
                }

                if($order['worker_money']>0){
                    User::money($order['worker_money'],$order['worker_id'],'订单完成,陪诊员收益');
                }

                if($order['agent_money']>0){
                    User::money($order['agent_money'],$order['agent_id'],'订单完成，城市代理人收益');
                }


                $order['status']=7;
                $order['complete_time']=time();
                $order->save();
            }

            //Db::rollback();
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('成功');
    }
}